package grammarbot;

import twitter4j.Twitter
import twitter4j.Query
import twitter4j.FilterQuery
import twitter4j.TwitterFactory
import twitter4j.TwitterStream
import twitter4j.TwitterStreamFactory
import twitter4j.conf.PropertyConfiguration

class TwitterUtils {

  /**
    *  Returns a filterQuery of all at tweets directed at bot.
    */
  def static filterQueryAtTweetingAccount(Twitter twitter) {
    new FilterQuery().track([twitter.screenName] as String[])
  }

  /**
    *  Returns a FilterQuery for streaming of all bot's followers.
    */
  def static filterQueryFollowers(Twitter twitter) {
    def ids = twitter.getFollowers().getIDs() // int[]
    new FilterQuery().follow(ids)
  }

  /**
    * Returns a configured instance of TwitterSteram.
    */
  def static getStreamInstance() {
    new TwitterStreamFactory(getConfiguration()).getInstance()
  }

  /**
    * Returns an instance of twitter configuration based on one of 
    * two mechanisms.
    *
    * If 'user' and 'password' are found in the Java system properties,
    * these are used, else ${user.home}/.grammarbot.properties is read for
    * 'user' and 'password' (or oauth, etc...). See twitter4j configuration
    * help for more information on the properties available in .grammarbot.properties.
    */
  def static getConfiguration() {
    def user = System.getProperty("user")
    def password = System.getProperty("password")
    def configuration = null
    if(user != null && password != null) {
      def properties = new Properties()
      properties.setProperty("user", user)
      properties.setProperty("password", password)
      configuration = new PropertyConfiguration(properties)      
    } else {
      def userHome = System.getProperty("user.home")
      def configFile = new File(userHome, ".grammarbot.properties")
      def inputStream = new FileInputStream(configFile)
      try {
        configuration = new PropertyConfiguration(inputStream)
      } finally {
        inputStream.close()
      }
    }
    configuration
  }

  /**
    * Returns a configured instance of twitter4j.Twitter
    */
  def static getInstance() {
    new TwitterFactory(getConfiguration()).getInstance()
  }

}